//
//  KWTPolicyDetailVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2024/10/15.
//

#import "KWTPolicyDetailVC.h"
#import "KWTPolicyListCell.h"
#import "KWTVppRecordDataCell.h"
#import "KWTVppSetRecordModel.h"
#import "KWTVppSetResultModel.h"
#import "KWTMGRNSettingModel.h"
#import "KWT233KSettingModel.h"
#import "RHSolarkSettingModel.h"
#import "RHVppSetCommonModel.h"
#import "SYChartTool.h"

@interface KWTPolicyDetailVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *resultArr;//下发结果

@property (nonatomic ,strong) NSArray *paraArr;//下发策略

@property (nonatomic ,strong) KWTVppSetRecordModel *headModel;

@end

@implementation KWTPolicyDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"策略详情".rh_localized;
    [self setupUI];
}

-(void)setRecordModel:(KWTVppSetRecordModel *)recordModel
{
    _recordModel = recordModel;
    [self getVppSetRecordDetail];
}

- (void)setupUI{
    kWeakSelf;
    self.recordModel.status = 2;
    [self updateRightButton];
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"setting_ao_mgrn_chg"];
    //去掉高级工作模式和和TOU时间使能
    NSArray *timeSetArr = @[[arr lastObject]];
   
    self.paraArr = [NSArray yy_modelArrayWithClass:[KWTMGRNSettingModel class] json:timeSetArr];
    //233的时间段设置与 S40K的不一样  (参数,时间段都不一样)
    if ([self.recordModel.deviceTypeCode is233DeviceType]) {
        [self build233VppParaModel];
    }else if ([self.recordModel.deviceTypeCode is61DeviceType]) {
        //61度电
        NSArray *arr = [SYChartTool loadJsonFileWithName:@"setting_me_solark_60k_chg"];
        self.paraArr = [NSArray yy_modelArrayWithClass:[RHSolarkSettingModel class] json:arr];
    }else if ([self.recordModel.deviceTypeCode isXStack]) {
        //储充一体  海索
        NSArray *arr = [SYChartTool loadJsonFileWithName:@"setting_ao_HiSolar_chg"];
        self.paraArr = [NSArray yy_modelArrayWithClass:[RHVppSetCommonModel class] json:arr];
    }
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView registerClass:[KWTPolicyListCell class] forCellReuseIdentifier:@"KWTPolicyListCell_detail"];
    [_tableView registerClass:[KWTVppRecordDataCell class] forCellReuseIdentifier:@"KWTVppRecordDataCell"];
    [self.view addSubview:_tableView];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(0);
        make.bottom.mas_offset(0);
    }];
    
    [_tableView addHeaderRefresh:^{
        
        [weakSelf getVppSetRecordDetail];
        
    }];
}

-(void)updateRightButton
{
    if (self.recordModel.status == 3) {//0 进行中 1 成功 2 部分成功 3失败
        UIBarButtonItem *rightButton = [UIBarButtonItem itemWithTitle:@"重新下发".rh_localized titleColor:kCOLOR_HEX(@"171A1D") titleFont:kSYSTEMFONT(14) Target:self Seletor:@selector(reSendPara)];
        self.navigationItem.rightBarButtonItem = rightButton;
    }else{
        self.navigationItem.rightBarButtonItem = nil;
    }
}

-(void)build233VppParaModel
{
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"setting_me_233_vpp_set"];
    NSArray *modelArr = [NSArray yy_modelArrayWithClass:[KWT233KSettingModel class] json:arr];
    //去掉模式
    NSMutableArray *mtbArr = [NSMutableArray arrayWithArray:modelArr];
    [mtbArr removeObjectAtIndex:0];
    self.paraArr = mtbArr.copy;
    //生成24个时间
    NSMutableArray *rowArr = [NSMutableArray array];
    [self.paraArr enumerateObjectsUsingBlock:^(KWT233KSettingModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([sectionModel.type isEqualToString:@"time"]) {
            KWT233KSettingModel *rowModel = [sectionModel.rows firstObject];
            KWT233KSettingModel *chgTagModel = [rowModel.items safeObjectAtIndex:0];
            KWT233KSettingModel *socModel = [rowModel.items safeObjectAtIndex:1];
            KWT233KSettingModel *powerModel = [rowModel.items safeObjectAtIndex:2];
            for (int i = 0; i <24; i++) {
                KWT233KSettingModel *rowNewModel = [[KWT233KSettingModel alloc]init];
                rowNewModel.type = rowModel.type;
                rowNewModel.comment = [NSString stringWithFormat:@"%02d:00-%02d:00",i,i+1];
                
                NSMutableArray *items = [NSMutableArray array];
                KWT233KSettingModel *chgTagNewModel = [[KWT233KSettingModel alloc]init];
                chgTagNewModel.selectList = chgTagModel.selectList.copy;
                chgTagNewModel.key     = chgTagModel.key;
                chgTagNewModel.type    = chgTagModel.type;
                
                KWT233KSettingModel *socNewModel = [[KWT233KSettingModel alloc]init];
                socNewModel.key     = [NSString stringWithFormat:@"%@%d",socModel.key,i+1];
                socNewModel.type    = socModel.type;
                
//                socNewModel.content = [NSString stringWithFormat:@"%u",arc4random_uniform(100)];
                KWT233KSettingModel *powerNewModel = [[KWT233KSettingModel alloc]init];
                powerNewModel.key     = [NSString stringWithFormat:@"%@%d",powerModel.key,i+1];
                powerNewModel.type    = powerModel.type;
                
//                powerNewModel.content = [NSString stringWithFormat:@"%u",arc4random_uniform(3000)];
                [items addObject:chgTagNewModel];
                [items addObject:socNewModel];
                [items addObject:powerNewModel];
                rowNewModel.items = items.copy;
                [rowArr addObject:rowNewModel];
            }
            sectionModel.rows = rowArr.copy;
        }
    }];
    
}

-(void)reSendPara
{
    [QMUITips showLoadingInView:self.view];
    [KWTVppSetRecordModel startGetWithCompletionAPIKey:H_groupVppReSend argument:@{@"id":@(self.recordModel.recordId)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"成功".rh_localized];
        }
     

    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
      
       
    }];
}
#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if(section == 1){
        return self.resultArr.count;
    }else{
        if ([self.recordModel.deviceTypeCode isEqualToString:@"S40K LV1.0"]) {
            KWTMGRNSettingModel *model = self.paraArr.firstObject;
            return model.rows.count;
        }else if ([self.recordModel.deviceTypeCode is233DeviceType]) {
            KWT233KSettingModel *model = self.paraArr.lastObject;//取时间段
            return model.rows.count;
        }else if([self.recordModel.deviceTypeCode is61DeviceType]){
            KWTMGRNSettingModel *model = self.paraArr.firstObject;
            return model.rows.count;
        }else if([self.recordModel.deviceTypeCode isXStack]){
            RHVppSetCommonModel *model = self.paraArr.firstObject;
            return model.rows.count;
        }
        
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section>0) {
        return 100;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return nil;
    }
    UIView *header = [self headerViewWithIndex:section];
    return header;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section>0) {
        return 20;
    }
    return 5;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 20)];
    footer.clipsToBounds = YES;
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, -8, kUI_WINDOW_W-30, 16)];
    [bgView round:8 RectCorners:kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner];
    bgView.backgroundColor = UIColor.whiteColor;
    [footer addSubview:bgView];
    return footer;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        KWTPolicyListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KWTPolicyListCell_detail"];
        [cell hideArrow];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.recordModel = self.headModel;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.section == 1){
        KWTVppRecordDataCell *dataCell = [tableView dequeueReusableCellWithIdentifier:@"KWTVppRecordDataCell"];
        dataCell.resultModel = [self.resultArr safeObjectAtIndex:indexPath.row];
        dataCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return dataCell;
    }else{
        KWTVppRecordDataCell *dataCell = [tableView dequeueReusableCellWithIdentifier:@"KWTVppRecordDataCell"];
        RHSolarkSettingModel *model = self.paraArr.lastObject;//取时间段
        if ([self.recordModel.deviceTypeCode isEqualToString:@"S40K LV1.0"]) {
            dataCell.paraS40KModel = [model.rows safeObjectAtIndex:indexPath.row];
        }else if ([self.recordModel.deviceTypeCode is233DeviceType]) {
            dataCell.para233Model = [model.rows safeObjectAtIndex:indexPath.row];
        }else if([self.recordModel.deviceTypeCode is61DeviceType]){
            dataCell.para61Model = [model.rows safeObjectAtIndex:indexPath.row];
        }else if([self.recordModel.deviceTypeCode isXStack]){
            dataCell.paraHiSolarkModel = [model.rows safeObjectAtIndex:indexPath.row];
        }
        
        dataCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return dataCell;
    }
   
    
    return [UITableViewCell new];
}


#pragma mark ---------- 获取分组设置记录详情 -----------
-(void)getVppSetRecordDetail
{
  
    [QMUITips showLoadingInView:self.view];
    
    
    NSDictionary *para = @{
                           @"id":@(self.recordModel.recordId)
    };
    

    [KWTVppSetRecordModel startGetWithCompletionAPIKey:H_vppSetRecordsDetail argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        [self.tableView endHeaderRefresh];
        self.headModel = [KWTVppSetRecordModel yy_modelWithJSON:request.responseObject];
        //下发结果
        self.resultArr = [NSArray yy_modelArrayWithClass:[KWTVppSetResultModel class] json:request.responseJSONObject[@"details"]];
        self.recordModel.status = [request.responseJSONObject[@"status"] integerValue];
        [self updateRightButton];
        
        //下发策略
        NSDictionary *dic = [request.responseJSONObject[@"strategy"] jsonStringToDictionary];
        
        NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
        NSArray *dicArr = dic[@"commandParamList"];
        [dicArr enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull paraDic, NSUInteger idx, BOOL * _Nonnull stop) {
            [mtbDic setObject:ValidNullData(paraDic[@"value"]) forKey:ValidNullData(paraDic[@"paramName"])];
        }];
        NSLog(@"---->%@",mtbDic);
        [self readDefult:mtbDic];
        [self.tableView reloadData];
     

    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
      
        [self.tableView endHeaderRefresh];
    }];
    
}

//读取默认值
- (void)readDefult:(NSDictionary *)dic{
    if ([self.recordModel.deviceTypeCode isEqualToString:@"S40K LV1.0"]) {
        [self.paraArr enumerateObjectsUsingBlock:^(KWTMGRNSettingModel*  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
            [model readDefult:dic];
        }];
    }else if ([self.recordModel.deviceTypeCode is233DeviceType]) {
        [self.paraArr enumerateObjectsUsingBlock:^(KWT233KSettingModel*  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
            [model readDefult:dic];
        }];
    }
    if ([self.recordModel.deviceTypeCode is61DeviceType]) {
        [self.paraArr enumerateObjectsUsingBlock:^(RHSolarkSettingModel*  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
            [model readDefult:dic];
        }];
    }
    if ([self.recordModel.deviceTypeCode isXStack]) {
        [self.paraArr enumerateObjectsUsingBlock:^(RHVppSetCommonModel*  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
            [model readHiSolarDefult:dic];
        }];
    }
    
}

-(UIView*)headerViewWithIndex:(NSInteger)section
{
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 100)];
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, 100)];
    [bgView setBackgroundColor:UIColor.whiteColor];
    [bgView round:8 RectCorners:kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner];
    [header addSubview:bgView];
    
    QMUILabel *titleLab = [QMUILabel labelWithFont:kBOLDSYSTEMFONT(16) textColor:kCOLOR_HEX(@"3F4443")];
    titleLab.text = section == 1?@"下发结果".rh_localized:@"下发策略".rh_localized;
    [bgView addSubview:titleLab];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_offset(15);
    }];
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX_A(@"#7E868E",0.2);
    [bgView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(1);
        make.top.equalTo(titleLab.mas_bottom).offset(15);
    }];
    
    UIView *optionView = kView;
    optionView.backgroundColor = CFTabViewBgColor;
    [bgView addSubview:optionView];
    [optionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(12);
        make.right.mas_offset(-12);
        make.top.equalTo(line.mas_bottom).offset(10);
        make.height.offset(35);
    }];
    
    NSArray *titles = @[@"站点".rh_localized,@"状态".rh_localized,@"成功(台)".rh_localized,@"失败(台)".rh_localized];
    if (section == 2) {
        BOOL is233 = [self.recordModel.deviceTypeCode is233DeviceType];
        
        titles = @[@"时段".rh_localized,@"状态".rh_localized,@"SOC(%)".rh_localized,[NSString stringWithFormat:@"%@%@",@"功率".rh_localized,is233?@"(kW)":@"(W)"]];
    }
    CGFloat labWidth = (kUI_WINDOW_W-30-20)/4;
    [titles enumerateObjectsUsingBlock:^(NSString*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUILabel *lab = [QMUILabel labelWithFont:kSYSTEMFONT(13) textColor:kCOLOR_HEX(@"#171A1D")];
        lab.text = obj;
        lab.adjustsFontSizeToFitWidth = YES;
        lab.minimumScaleFactor = 0.8;
        [optionView addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(idx*labWidth);
            make.centerY.mas_offset(0);
            make.width.offset(labWidth);
        }];
    }];
    
    return header;
}

@end
